import logging

from django.shortcuts import redirect
from django.views.decorators.cache import cache_page
from django.utils import simplejson
from django.http import HttpResponse, HttpResponseRedirect
from django import forms

from brispon.util.decorators import render_to, ajax_request
from brispon.models import Event, FavoriteCoupon, FavoriteStore
from brispon.util import BaseSearchForm, paginate, inc_paginate
from brispon.models import Event, Keyword, SiteUser

class EventForm(BaseSearchForm):
    class Meta:
        base_qs = Event.objects
        search_fields = ('searchable',) 
        default_fields = {'!active': True}


class UserForm(forms.Form):
    mobile = forms.CharField(max_length=10)
    email = forms.EmailField()
    
    def clean_mobile(self):
        data = self.cleaned_data['mobile']
        if len(data) != 10:
            raise forms.ValidationError("Wrong Mobile Number.")
        if not data.startswith('0'):
            raise forms.ValidationError("Wrong Mobile Number.")
        
        if not data.isdigit():
            raise forms.ValidationError("Wrong Mobile Number.")

        return data


#@cache_page(60 * 60)
@render_to('d/index.html')
def index(request):
    if request.is_mobile:
        return redirect('brispon.views.mindex')
    event_form = EventForm(request.GET or None)
    mevents = Event.objects.get_mevents().order_by('?')
    return {
            'mevents': mevents,
            'search_form': event_form
            }
    
# mobile
def mindex(request):
    if not request.is_mobile:
        return redirect('brispon.views.index')
    #return redirect('brispon.views.event.mlist')
    return redirect('brispon.views.store.mlist') 

@cache_page(60 * 60) 
@render_to('d/event/inc_list.html')
def inc_list(request):
    event_form = EventForm(request.GET or None)
    return inc_paginate(request.GET, search_form=event_form)

@cache_page(60 * 60)
@ajax_request
def lookup(request):
    term = request.REQUEST['term']
    keywords = Keyword.objects.search(term=term)
    terms = [k.term for k in keywords]
    json = simplejson.dumps(terms)
    return HttpResponse(json, mimetype='application/json')

@render_to('d/user.html')
def user_info(request):
    if request.is_mobile:
        return redirect('brispon.views.muser_info')
        
    siteuser = SiteUser.objects.get(user=request.user)
    if request.method == 'POST':
        user_form = UserForm(request.POST)
        if user_form.is_valid():
            siteuser.mobile = user_form.cleaned_data['mobile']
            request.user.email = user_form.cleaned_data['email']
            siteuser.save()
            request.user.save()
        redirect('brispon.views.user_info')
    else:
        user_form = UserForm({'mobile':siteuser.mobile, 'email':request.user.email})
        
    fcoupons = FavoriteCoupon.objects.filter(user=request.user)[:10]
    fstores = FavoriteStore.objects.filter(user=request.user)
    return {
            'user_form':user_form,
            'fcoupons': fcoupons,
            'fstores': fstores,
            }

@render_to('m/user.html')
def muser_info(request):
    if not request.is_mobile:
        return redirect('brispon.views.user_info')
    fcoupons = FavoriteCoupon.objects.filter(user=request.user)
    fstores = FavoriteStore.objects.filter(user=request.user)
    return {
            'fcoupons': fcoupons,
            'fstores': fstores,
            }

@render_to('d/contract.html')
def contract(request):
    if request.is_mobile:
        return redirect('brispon.views.mcontract')
    return {}

@render_to('m/contract.html')
def mcontract(request):
    if not request.is_mobile:
        return redirect('brispon.views.contract')
    return {}
